package net.cattaka.teamredwhite.web;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import net.cattaka.teamredwhite.TeamRedWhite;

import android.content.Context;
import android.os.Environment;

public class ImageContent extends AbstractContent {
	public ImageContent(Context context) {
		super(context);
	}

	@Override
	public void handle(String path, Map<String, String> params, InputStream in, OutputStream out) throws IOException {
		String file = params.get("file");

		// 下準備、静的HTMLの長さの取得(良い方法ないんかな・・・？)
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		{
			File exDir = Environment.getExternalStorageDirectory();
			File targetFile = new File(exDir.getPath() + File.separator + TeamRedWhite.IMAGE_PATH + File.separatorChar + file);
			InputStream fileIn = new FileInputStream(targetFile);
			try {
				int r = 0;
				while ((r=fileIn.read()) != -1) {
					bout.write((byte)r);
				}
			} finally {
				if (fileIn != null) {
					fileIn.close();
				}
			}
		}
		
		// ステータスラインとヘッダーの出力
		String mime;
		if (file.toLowerCase().endsWith(".png")) {
			mime = "image/png";
		} else if (file.toLowerCase().endsWith(".jpg") || file.toLowerCase().endsWith(".jpeg")) {
			mime = "image/png";
		} else {
			// ありえんので適当
			mime = "application/octet-stream";
		}
		
		ContentWriter.outputResponseHeader(out, 200, mime, bout.size());
		
		// 実データの出力
		out.write(bout.toByteArray());
	}
}
